﻿using Application.IService.User;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Security.Claims;
using System.Security;
using Application.IService.Role;
using Domain.Entity.User;
using Application.IService.Permission;
using Domain.Entity.Permission;

namespace ApiServer.Auth
{
    /// <summary>
    /// 授权处理（自定义策略授权）
    /// </summary>
    public class PermissionAuthorizationHandler : AuthorizationHandler<PermissionAuthorizationRequirement>
    {
        private readonly IUserService _userService;
        private readonly ILogger<PermissionAuthorizationHandler> _logger;
        private readonly IRoleUsersService roleUsers;
        private readonly IRolePermissionService rolePermission;
        private readonly IPermissionService permission;


        /// <summary>
        /// 构造方法
        /// </summary>
        public PermissionAuthorizationHandler(IUserService userService,
                                              ILogger<PermissionAuthorizationHandler> logger
,
                                              IRoleUsersService roleUsers,
                                              IRolePermissionService rolePermission,
                                              IPermissionService permission)
        {
            this._userService = userService; //依赖注入
            _logger = logger;
            this.roleUsers = roleUsers;
            this.rolePermission = rolePermission;
            this.permission = permission;
        }

        /// <summary>
        /// 处理授权条件
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       PermissionAuthorizationRequirement requirement)
        {
            //判断登录用户是否为空
            if (context.User != null)
            {
                if (context.User.IsInRole("admin")) //如果是管理员，则不检查权限
                {
                    context.Succeed(requirement);
                }
                else
                {
                    //获取用户主键
                    var userIdClaim = context.User.FindFirst(s => s.Type == ClaimTypes.NameIdentifier);
                    int UserId;
                    if (!int.TryParse(userIdClaim.Value, out UserId)) //获取用户主键
                    {
                        return Task.CompletedTask;
                    }
                    //查询数据库
                    var userrole = roleUsers.GetAll().Result.ToList();
                    var rolepermission = rolePermission.GetAll().Result.ToList();
                    var permissionlist = permission.GetAll().Result.ToList();

                    //根据用户ID查角色ID
                    List<int> rolelist = userrole.Where(a => a.UserId == UserId).Select(a=>(int)a.RoleId).ToList();

                    //根据角色ID查权限ID
                    List<int> permissionidlist = new List<int>();
                    foreach (var item in rolelist)
                    {
                        var ids= rolepermission.Where(a => a.RoleId == item).Select(a => a.PermissionId);
                        foreach (var item2 in ids)
                        {
                            permissionidlist.Add((int)item2);
                        }
                    }
                    //权限ID去重
                    permissionidlist=permissionidlist.Distinct().ToList();

                    //根据权限ID找权限信息
                    List<PermissionInfo> permissioninfo = new List<PermissionInfo>();
                    foreach (var item in permissionidlist)
                    {
                        permissioninfo.Add(permissionlist.Where(a => a.Id == item).FirstOrDefault());
                    }


                    //string requestUrl = requirement.Path.TrimEnd('/').ToLower(); //获取请求的api路径
                    //if (permissioninfo.Select(x => x.ApiAction?.ToLower()).Contains(requestUrl))
                    //{
                    //   context.Succeed(requirement);
                    //}
                    //else
                    //{
                    //    _logger.LogWarning("用户试图访问没有被授权的Api接口");
                    //}
                }
            }

            return Task.CompletedTask;
        }
    }
}
